#include "doubly_linked_list.h"

Link *insert(Link *p, Link *n)
{
    if (n == nullptr)
        return n;
    if (p == nullptr)
        return p;
    n->succ = p;
    if (p->prev)
        p->prev->succ = n;
    n->prev = p->prev;
    p->prev = n;
    return n;
}

Link *add(Link *p, Link *n)
{
    if (n == nullptr)
        return n;
    if (p == nullptr)
        return p;
    n->succ = p->succ;
    n->prev = p;
    if (p->succ)
        p->succ->prev = n;
    p->succ = n;
    return n;
}
Link *erase(Link *p)
{
    if (p == nullptr)
        return nullptr;
    if (p->succ)
        p->succ->prev = p->prev;
    if (p->prev)
        p->prev->succ = p->succ;
    return p->succ;
}
Link *find(Link *p, const std::string &s)
{
    while (p)
    {
        if (p->value == s)
            return p;
        p = p->succ;
    }
    return nullptr;
}

Link *advance(Link *p, int n)
{
    if (p == nullptr)
        return nullptr;
    if (n > 0)
    {
        while (n--)
        {
            if (p->succ == nullptr)
                return nullptr;
            p = p->succ;
        }
    }
    else if (n < 0)
    {
        while (n++)
        {
            if (p->prev == nullptr)
                return nullptr;
            p = p->prev;
        }
    }
    return p;
}